package cn.wx;

import cn.wx.common.WxServiceRegister;
import cn.wx.common.WxServiceRegisterPostProcessor;
import cn.wx.common.properties.WxProperties;
import cn.wx.properties.WxOpenProperties;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.open.api.WxOpenConfigStorage;
import me.chanjar.weixin.open.api.WxOpenService;
import me.chanjar.weixin.open.api.impl.WxOpenServiceImpl;
import org.springframework.core.annotation.Order;
import org.springframework.util.CollectionUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static cn.wx.properties.WxOpenProperties.PREFIX;

/**
 * 微信公众平台注册,使用配置文件的方式
 *
 * @author: sunshaoping
 * @date: Create by in 5:11 下午 2020/5/25
 */
@Order(9)
@AllArgsConstructor
public class WxOpenServiceRegisterPostProcessor implements WxServiceRegisterPostProcessor {

    private final WxOpenProperties properties;

    private final WxOpenConfigStorageFactory<WxProperties> wxOpenConfigStorageFactory;

    @Override
    public void processor(WxServiceRegister wxServiceRegister) {
        //默认服务
        properties.verification(PREFIX);
        final WxOpenService wxMaService = createWxMaService(properties);
        //注册默认bean
        wxServiceRegister.register(properties.getName(), wxMaService);

        List<WxProperties> multiple = properties.getMultiple();
        if (CollectionUtils.isEmpty(multiple)) {
            return;
        }

        Set<String> set = new HashSet<>(multiple.size() + 1);
        set.add(properties.getName());
        for (int i = 0; i < multiple.size(); i++) {
            WxProperties wxMaProperties = multiple.get(i);
            String name = wxMaProperties.getName();
            String prefix = PREFIX + ".multiple[" + i + "]";
            wxMaProperties.verification(prefix);
            final WxOpenService service = createWxMaService(wxMaProperties);
            if (set.contains(name)) {
                throw new IllegalStateException(prefix + ".name=" + name + ",已存在 ");
            }
            set.add(name);
            //注册bean
            wxServiceRegister.register(name, service);
        }
    }

    public WxOpenService createWxMaService(WxProperties properties) {
        WxOpenConfigStorage config = wxOpenConfigStorageFactory.create(properties);
        final WxOpenService service = new WxOpenServiceImpl();
        service.setWxOpenConfigStorage(config);
        return service;
    }
}
